package com.xxl.job.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.dimples.dd.common.constant.DDServerConstant;
import com.dimples.dd.common.pojo.PageParam;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.common.result.CommonResult;
import com.dimples.dd.log.core.annotation.ApiLog;
import com.xxl.job.admin.core.exception.XxlJobException;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.route.ExecutorRouteStrategyEnum;
import com.xxl.job.admin.core.scheduler.MisfireStrategyEnum;
import com.xxl.job.admin.core.scheduler.ScheduleTypeEnum;
import com.xxl.job.admin.core.thread.JobScheduleHelper;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.service.LoginService;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.glue.GlueTypeEnum;
import com.xxl.job.core.util.DateUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * index controller
 *
 * @author xuxueli 2015-12-19 16:13:16
 */
@Tag(name = "任务管理")
@Controller
@RequestMapping("/job-info")
public class JobInfoController {
    private static final Logger logger = LoggerFactory.getLogger(JobInfoController.class);

    @Resource
    private XxlJobGroupDao xxlJobGroupDao;
    @Resource
    private XxlJobService xxlJobService;

    @RequestMapping
    public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) {

        // 枚举-字典
        model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values());        // 路由策略-列表
        model.addAttribute("GlueTypeEnum", GlueTypeEnum.values());                                // Glue类型-字典
        model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values());        // 阻塞处理策略-字典
        model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values());                        // 调度类型
        model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values());                    // 调度过期策略

        // 执行器列表
        List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll();

        // filter group
        List<XxlJobGroup> jobGroupList = filterJobGroupByRole(request, jobGroupList_all);
        if (jobGroupList == null || jobGroupList.isEmpty()) {
            throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
        }

        model.addAttribute("JobGroupList", jobGroupList);
        model.addAttribute("jobGroup", jobGroup);

        return "jobinfo/jobinfo.index";
    }

    public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all) {
        List<XxlJobGroup> jobGroupList = new ArrayList<>();
        if (jobGroupList_all != null && !jobGroupList_all.isEmpty()) {
            XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
            if (loginUser.getRole() == 1) {
                jobGroupList = jobGroupList_all;
            } else {
                List<String> groupIdStrs = new ArrayList<>();
                if (loginUser.getPermission() != null && !loginUser.getPermission().trim().isEmpty()) {
                    groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(","));
                }
                for (XxlJobGroup groupItem : jobGroupList_all) {
                    if (groupIdStrs.contains(String.valueOf(groupItem.getId()))) {
                        jobGroupList.add(groupItem);
                    }
                }
            }
        }
        return jobGroupList;
    }

    public static void validPermission(HttpServletRequest request, int jobGroup) {
        XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
        if (!loginUser.validPermission(jobGroup)) {
            throw new RuntimeException(I18nUtil.getString("system_permission_limit") + "[username=" + loginUser.getUsername() + "]");
        }
    }

    @Operation(summary = "查询任务列表")
    @GetMapping("/page")
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:query')")
    public PageResult<XxlJobInfo> pageList(PageParam pageParam,
                                           @RequestParam(defaultValue = "0") int jobGroup,
                                           @RequestParam(defaultValue = "-1") int triggerStatus,
                                           String jobDesc,
                                           String executorHandler,
                                           String author) {

        return xxlJobService.pageList(pageParam, jobGroup, triggerStatus, jobDesc, executorHandler, author);
    }

    @Operation(summary = "创建任务")
    @PostMapping
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:create')")
    public CommonResult<String> add(@RequestBody XxlJobInfo jobInfo) {
        ReturnT<String> add = xxlJobService.add(jobInfo);
        return add.getCode() == ReturnT.SUCCESS_CODE ? CommonResult.success(add.getContent()) : CommonResult.error(add.getMsg());
    }

    @Operation(summary = "更新任务")
    @PutMapping("{id}")
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:update')")
    public CommonResult<String> update(@PathVariable Integer id, @RequestBody XxlJobInfo jobInfo) {
        jobInfo.setId(id);
        ReturnT<String> update = xxlJobService.update(jobInfo);
        return update.getCode() == ReturnT.SUCCESS_CODE ? CommonResult.success(update.getContent()) : CommonResult.error(update.getMsg());
    }

    @Operation(summary = "删除任务")
    @DeleteMapping("{id}")
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:delete')")
    public CommonResult<String> remove(@PathVariable String id) {
        ReturnT<String> remove = xxlJobService.remove(StrUtil.split(id, StrUtil.COMMA));
        return remove.getCode() == ReturnT.SUCCESS_CODE ? CommonResult.success(remove.getContent()) : CommonResult.error(remove.getMsg());
    }

    @Operation(summary = "停止任务")
    @PostMapping("/stop")
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:stop')")
    public CommonResult<String> pause(int id) {
        ReturnT<String> stop = xxlJobService.stop(id);
        return stop.getCode() == ReturnT.SUCCESS_CODE ? CommonResult.success(stop.getContent()) : CommonResult.error(stop.getMsg());
    }

    @Operation(summary = "启动任务")
    @PostMapping("/start")
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:start')")
    public CommonResult<String> start(int id) {
        ReturnT<String> start = xxlJobService.start(id);
        return start.getCode() == ReturnT.SUCCESS_CODE ? CommonResult.success(start.getContent()) : CommonResult.error(start.getMsg());
    }

    @Operation(summary = "任务执行一次")
    @PostMapping("/trigger")
    @ResponseBody
    @ApiLog(applicationName = DDServerConstant.DD_XXL_JOB, responseEnable = true)
    @PreAuthorize("@ss.hasPerm('system:job-info:start')")
    public CommonResult<String> triggerJob(HttpServletRequest request, int id, String executorParam, String addressList) {
        // login user
        XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
        // trigger
        ReturnT<String> trigger = xxlJobService.trigger(loginUser, id, executorParam, addressList);
        return trigger.getCode() == ReturnT.SUCCESS_CODE ? CommonResult.success(trigger.getContent()) : CommonResult.error(trigger.getMsg());
    }

    @PostMapping("/nextTriggerTime")
    @ResponseBody
    public CommonResult<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {

        XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
        paramXxlJobInfo.setScheduleType(scheduleType);
        paramXxlJobInfo.setScheduleConf(scheduleConf);

        List<String> result = new ArrayList<>();
        try {
            Date lastTime = new Date();
            for (int i = 0; i < 5; i++) {
                lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
                if (lastTime != null) {
                    result.add(DateUtil.formatDateTime(lastTime));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return CommonResult.error(String.valueOf(ReturnT.FAIL_CODE), (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")) + e.getMessage());
        }
        return CommonResult.success(result);

    }

}
